import java.io.*;
import java.util.Arrays;

///Users/edz/banyuan/Java/19.IO/doc/WIN.mp3
public class Main {
    public static void main(String[] args) throws IOException {
        File sourceFile = new File("/Users/edz/banyuan/Java/19.IO/doc/WIN.mp3");
        File targetFolder = new File("/Users/edz/banyuan/Java/19.IO/doc");
        int size = 8000;
        split(sourceFile, size, targetFolder);

        File sourceFile1 = new File("/Users/edz/banyuan/Java/19.IO/doc");
        File targetFile1 = new File("/Users/edz/banyuan/Java/19.IO/doc/temp.mp3");
        combine(sourceFile1, targetFile1);
    }

    static void split(File sourceFile, int size, File targetFolder) throws IOException {
        // 拆分之后的文件数
        int Number = (int) (sourceFile.length() / size);
        if (sourceFile.length() % size != 0) {
            Number = Number + 1;
        }

        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(sourceFile));
        BufferedOutputStream[] bufferedOutputStreams = new BufferedOutputStream[Number];

        for (int i = 0; i < Number; i++) {
            bufferedOutputStreams[i] = new BufferedOutputStream(new FileOutputStream(targetFolder + "/" + sourceFile.getName() + "." + (i + 1)));
            int read = bufferedInputStream.read();
            int limit = 0;                              // 写入的字节数量
            while (read != -1) {
                bufferedOutputStreams[i].write(read);
                limit++;
                if (limit == size) {
                    break;
                }
                read = bufferedInputStream.read();
            }
            bufferedOutputStreams[i].flush();
            bufferedOutputStreams[i].close();
        }
        bufferedInputStream.close();
    }

    static void combine(File sourceFolder, File targetFolder) throws IOException {
        int Number = 0;
        for (String s : sourceFolder.list()) {
            if (s.startsWith("WIN.mp3.")) {
                Number++;
            }
        }
        BufferedInputStream[] bufferedInputStreams = new BufferedInputStream[Number];
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(targetFolder));
        for (int i = 0; i < Number; i++) {
            bufferedInputStreams[i] = new BufferedInputStream(new FileInputStream((sourceFolder) + "/WIN.mp3." + (i + 1)));
            int read = bufferedInputStreams[i].read();
            while (read != -1) {
                bufferedOutputStream.write(read);
                read = bufferedInputStreams[i].read();
            }
            bufferedOutputStream.flush();
            bufferedInputStreams[i].close();
        }
        bufferedOutputStream.close();
    }
}
